package com.cgnpc.scp.hse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.utils.AjaxResultUtil;
import com.cgnpc.scp.common.utils.ListUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.hse.mybatis.entity.HseCommonCheckOptionsConfig;
import com.cgnpc.scp.hse.mybatis.entity.HseMeetingInfo;
import com.cgnpc.scp.hse.mybatis.mapper.client.HseCommonCheckOptionsConfigMapper;
import com.cgnpc.scp.hse.service.IHseCommonCheckOptionsConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

@Service
public class HseCommonCheckOptionsConfigServiceImpl implements IHseCommonCheckOptionsConfigService {
    private static final Logger LOGGER = LoggerFactory.getLogger(HseCommonCheckOptionsConfigServiceImpl.class);

    @Autowired
    private MessageSource messageSource;

    @Autowired
    private HseCommonCheckOptionsConfigMapper hseCommonCheckOptionsConfigMapper;

    @Override
    public <T extends HseCommonCheckOptionsConfig> List<T> loadMenu() {
        List<HseCommonCheckOptionsConfig> usedOptionList = new ArrayList<>();

        QueryWrapper<HseCommonCheckOptionsConfig> queryWrapper = new QueryWrapper<>();

        queryWrapper.orderByAsc("order_index");

        List<HseCommonCheckOptionsConfig> dbOptionList = hseCommonCheckOptionsConfigMapper.selectList(queryWrapper);

        if (ListUtil.getListSizeWith0(dbOptionList) > 0) {
            usedOptionList.addAll(dbOptionList);

            Map<String, HseCommonCheckOptionsConfig> optionIdWithObjectMap = new HashMap<>();

            for (HseCommonCheckOptionsConfig dbOption : dbOptionList) {
                optionIdWithObjectMap.put(dbOption.getId(), dbOption);
            }

            HseCommonCheckOptionsConfig optionParent = null;

            for (HseCommonCheckOptionsConfig dbOption : dbOptionList) {
                optionParent = optionIdWithObjectMap.get(dbOption.getParentId());

                if (optionParent != null) {
                    if (optionParent.getChildren() == null) {
                        optionParent.setChildren(new ArrayList<>());
                    }

                    optionParent.getChildren().add(dbOption);
                    usedOptionList.remove(dbOption);
                }
            }
        }

        return (List<T>) usedOptionList;
    }

    @Override
    public <T extends HseCommonCheckOptionsConfig> List<T> loadListByMeetingType(Integer meetingType) {
        if (meetingType == null) {
            return null;
        }

        List<HseCommonCheckOptionsConfig> resultList = new ArrayList<>();
        String optionId = null;

        // meeting_type 会议类型；值1班前会；2工前会；
        if (meetingType == HseMeetingInfo.MEETINGTYPE_1) {
            optionId = HseCommonCheckOptionsConfig.MEETING_TYPE_1_PRE_SHIFT_MEETING;
        } else if (meetingType == HseMeetingInfo.MEETINGTYPE_2) {
            optionId = HseCommonCheckOptionsConfig.MEETING_TYPE_2_PRE_JOB_BRIEFING;
        }

        if (StringUtil.isNullOrSpace(optionId)) {
            return null;
        }

        List<String> usedOptionIdList = new ArrayList<>();
        usedOptionIdList.add(optionId);

        if (ListUtil.getListSizeWith0(usedOptionIdList) > 0) {
            String usedOptionId = null;
            List<HseCommonCheckOptionsConfig> dbOptionList = null;

            while (ListUtil.getListSizeWith0(usedOptionIdList) > 0) {
                usedOptionId = usedOptionIdList.remove(0);

                QueryWrapper<HseCommonCheckOptionsConfig> queryWrapper = new QueryWrapper<>();

                queryWrapper.eq("parent_id", usedOptionId);

                dbOptionList = hseCommonCheckOptionsConfigMapper.selectList(queryWrapper);

                if (ListUtil.getListSizeWith0(dbOptionList) > 0) {
                    resultList.addAll(dbOptionList);

                    for (HseCommonCheckOptionsConfig dbOption : dbOptionList) {
                        usedOptionIdList.add(dbOption.getId());
                    }
                }
            }
        }

        return (List<T>) resultList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public <T extends HseCommonCheckOptionsConfig> AjaxResult saveOrUpdate(UserInfo loginUserInfo, Locale reqLocale, List<T> reqEntityList) {
        final String logInfo = "[HseCommonCheckOptionsConfig_saveOrUpdate_UUID_" + UUID.randomUUID().toString() + "]";
        AjaxResult ajaxResult = null;

        try {
            Date nowDate = new Date();
            // begin 获取登录用户的信息
            String loginUserInfoUserId = loginUserInfo.getUserId();
            String loginUserInfoUserName = loginUserInfo.getUserName();
            // end 获取登录用户的信息

            T usedEntity = null;
            int saveRows = 0;
            int updateRows = 0;

            String reqId = null;
            String reqEntityParentId = null;
            String reqEntityOptionText = null;
            String reqEntityOptionTextEn = null;
            String reqEntityOptionValue = null;
            Integer reqEntityNeedInspection = null;
            Integer reqEntityOrderIndex = null;

            for (T reqEntity : reqEntityList) {
                reqId = reqEntity.getId();
                reqEntityParentId = reqEntity.getParentId();
                reqEntityOptionText = reqEntity.getOptionText();
                reqEntityOptionTextEn = reqEntity.getOptionTextEn();
                reqEntityOptionValue = reqEntity.getOptionValue();
                reqEntityNeedInspection = reqEntity.getNeedInspection();
                reqEntityOrderIndex = reqEntity.getOrderIndex();

                if (StringUtil.isNullOrSpace(reqId)) {
                    // 保存
                    usedEntity = (T) new HseCommonCheckOptionsConfig();
                    // 设置主键
                    usedEntity.setId(IDHelper.uuidNew());
                    // 设置父id
                    usedEntity.setParentId(reqEntityParentId);
                    // 设置排序
                    usedEntity.setOrderIndex(reqEntityOrderIndex != null ? reqEntityOrderIndex : 1);
                    // 设置显示的中文
                    usedEntity.setOptionText(reqEntityOptionText);
                    // 设置显示的英文
                    usedEntity.setOptionTextEn(reqEntityOptionTextEn);
                    // 设置值
                    usedEntity.setOptionValue(reqEntityOptionValue);
                    // 设置是否检查
                    usedEntity.setNeedInspection(reqEntityNeedInspection);

                    // begin 设置公共字段
                    // create_time 创建时间
                    usedEntity.setCreateTime(nowDate);
                    // create_user 创建人员工号
                    usedEntity.setCreateUser(loginUserInfoUserId);
                    // create_user_name 创建人姓名，例如：[P206992]张平
                    usedEntity.setCreateUserName(loginUserInfoUserName);
                    // last_update_time 更新时间
                    usedEntity.setLastUpdateTime(nowDate);
                    // last_update_user 更新人员工号
                    usedEntity.setLastUpdateUser(loginUserInfoUserId);
                    // last_update_user_name 更新人姓名，例如：[P206992]张平
                    usedEntity.setLastUpdateUserName(loginUserInfoUserName);
                    // end 设置公共字段

                    saveRows += hseCommonCheckOptionsConfigMapper.insert(usedEntity);
                } else {
                    // 修改
                    usedEntity = (T) new HseCommonCheckOptionsConfig();
                    // 设置主键
                    usedEntity.setId(reqId); // id用于更新
                    // 设置父id
                    usedEntity.setParentId(reqEntityParentId);
                    // 设置排序
                    usedEntity.setOrderIndex(reqEntityOrderIndex);
                    // 设置显示的中文
                    usedEntity.setOptionText(reqEntityOptionText);
                    // 设置显示的英文
                    usedEntity.setOptionTextEn(reqEntityOptionTextEn);
                    // 设置值
                    usedEntity.setOptionValue(reqEntityOptionValue);
                    // 设置是否检查
                    usedEntity.setNeedInspection(reqEntityNeedInspection);

                    // begin 设置公共字段
                    // create_time 创建时间
                    // usedEntity.setCreateTime(nowDate);
                    // create_user 创建人员工号
                    // usedEntity.setCreateUser(loginUserInfoUserId);
                    // create_user_name 创建人姓名，例如：[P206992]张平
                    // usedEntity.setCreateUserName(loginUserInfoUserName);
                    // last_update_time 更新时间
                    usedEntity.setLastUpdateTime(nowDate);
                    // last_update_user 更新人员工号
                    usedEntity.setLastUpdateUser(loginUserInfoUserId);
                    // last_update_user_name 更新人姓名，例如：[P206992]张平
                    usedEntity.setLastUpdateUserName(loginUserInfoUserName);
                    // end 设置公共字段

                    updateRows += hseCommonCheckOptionsConfigMapper.updateById(usedEntity);
                }
            }

            String strResultInfo = "保存" + saveRows + "行；修改" + updateRows + "行；";

            ajaxResult = AjaxResultUtil.createSuccessMessage(strResultInfo);
        } catch (Exception e) {
            LOGGER.error("{}error;", logInfo, e);
            throw e;
        }

        return ajaxResult;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public <T extends HseCommonCheckOptionsConfig> AjaxResult delById(UserInfo loginUserInfo, Locale reqLocale, List<String> reqIdList) {
        final String logInfo = "[HseCommonCheckOptionsConfig_delById_UUID_" + UUID.randomUUID().toString() + "]";
        AjaxResult ajaxResult = null;

        try {
            if (ListUtil.getListSizeWith0(reqIdList) <= 0) {
                return AjaxResultUtil.createI18nErrorDefaultMessage(reqLocale, messageSource);
            }

            List<String> notDelIdList = Arrays.asList(
                    HseCommonCheckOptionsConfig.MEETING_TYPE_1_PRE_SHIFT_MEETING,
                    HseCommonCheckOptionsConfig.MEETING_TYPE_2_PRE_JOB_BRIEFING
            );

            reqIdList.removeAll(notDelIdList);

            if (ListUtil.getListSizeWith0(reqIdList) <= 0) {
                return AjaxResultUtil.createI18nErrorDefaultMessage(reqLocale, messageSource);
            }

            QueryWrapper<HseCommonCheckOptionsConfig> queryWrapper = new QueryWrapper<>();

            queryWrapper.notIn("id", notDelIdList);
            queryWrapper.in("id", reqIdList);

            List<HseCommonCheckOptionsConfig> dbHseCommonCheckOptionsConfigList = hseCommonCheckOptionsConfigMapper.selectList(queryWrapper);

            if (ListUtil.getListSizeWith0(dbHseCommonCheckOptionsConfigList) <= 0) {
                return AjaxResultUtil.createI18nSuccessDefaultMessage(reqLocale, messageSource);
            }

            for (HseCommonCheckOptionsConfig dbOptionConfig : dbHseCommonCheckOptionsConfigList) {
                String dbOptionConfigId = dbOptionConfig.getId();

                QueryWrapper<HseCommonCheckOptionsConfig> childrenQueryWrapper = new QueryWrapper<>();

                childrenQueryWrapper.eq("parent_id", dbOptionConfigId);

                List<HseCommonCheckOptionsConfig> dbChildOptionConfigList = hseCommonCheckOptionsConfigMapper.selectList(childrenQueryWrapper);

                if (ListUtil.getListSizeWith0(dbChildOptionConfigList) > 0) {
                    List<String> newIdList = new ArrayList<>();

                    for (HseCommonCheckOptionsConfig dbChildOptionConfig : dbChildOptionConfigList) {
                        newIdList.add(dbChildOptionConfig.getId());
                    }

                    delById(loginUserInfo, reqLocale, newIdList);
                }

                // 删除节点
                UpdateWrapper<HseCommonCheckOptionsConfig> delWrapper = new UpdateWrapper<>();

                delWrapper.notIn("id", notDelIdList);
                delWrapper.eq("id", dbOptionConfigId);

                hseCommonCheckOptionsConfigMapper.delete(delWrapper);
            }

            ajaxResult = AjaxResultUtil.createI18nSuccessDefaultMessage(reqLocale, messageSource);
        } catch (Exception e) {
            LOGGER.error("{}error;", logInfo, e);
            throw e;
        }

        return ajaxResult;
    }

}
